<template>
  <div class="login-box">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >

        <el-button @click="toGiteeView">gitee login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { apiLogin, apigiteeLogin } from "@/api";
import Cookie from "js-cookie";

export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
        ],
      },
    };
  },
  created() {
    // 判断地址栏参数中是否有code参数 如果有code参数 就代表是第三方认证回来的页面
    console.log(this.$route);
    apigiteeLogin({ code: this.$route.query.code }).then((res) => {
      // 保存token
      Cookie.set("token", res.token);

      // 提示登录成功
      this.$message({
        type: "success", // success error warning
        message: "登录成功",
        duration: 2000,
      });

      // 跳转页面
      window.location.href = "/";
    });
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((isRule) => {
        if (isRule) {
          // 发送登录请求
          apiLogin(this.ruleForm).then((res) => {
            // 保存token
            Cookie.set("token", res.token);

            // 提示登录成功
            this.$message({
              type: "success", // success error warning
              message: "登录成功",
              duration: 2000,
            });

            // 跳转页面
            window.location.href = "/";
          });
        }
      });
    },
    // 将用户引导到第三方认证页面
    toGiteeView() {
      window.location.href =
        "https://gitee.com/oauth/authorize?client_id=d38d8fd6243ccb93f0076f02c57336de802491411f650b2b18af8c2a59d98719&redirect_uri=http://10.1.33.16:8080/login&response_type=code";
    },
  },
};
</script>
